package com.mall.shopping.services;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class ICartServiceImpl implements ICartService {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    ItemMapper itemMapper;

    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse response = new CartListByIdResponse();
        try {

            long userId = request.getUserId();
            RMap<String, String> rMap = redissonClient.getMap(String.valueOf(userId));
            List<CartProductDto> cartProductDtoList = new ArrayList<>();
            for (String productId : rMap.keySet()) {
                String cartChildrenString = rMap.get(productId);
                CartProductDto cartProductDto =JSONObject.parseObject(cartChildrenString, CartProductDto.class);
                cartProductDtoList.add(cartProductDto);
            }
            response.setCartProductDtos(cartProductDtoList);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getCode());
        }
        return response;
    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse response = new AddCartResponse();
        try {
            Long userId = request.getUserId();
            //获取用户购物车数据,map对应productId和商品信息
            RMap<String, String> rMap = redissonClient.getMap(String.valueOf(userId));
            //遍历查询当前添加的商品购物车里面有没有,如果有需要进行合并
            Set<String> products = rMap.keySet();
            for (String productId : products) {
                //将新增的数量更新到购物车,添加结束
                if(request.getProductId()==Long.parseLong(productId)){
                    String s = rMap.get(productId);
                    JSONObject jsonObject = JSON.parseObject(s);
                    Long productNum = Long.parseLong((String) jsonObject.get("productNum"));
                    jsonObject.put("productNum",productNum+request.getProductNum());
                    rMap.put(productId,JSON.toJSONString(jsonObject));
                    response.setCode(ShoppingRetCode.SUCCESS.getCode());
                    response.setMsg(ShoppingRetCode.SUCCESS.getCode());
                    return response;
                }
            }
            //这个商品是一个新的商品,新增数据
            CartProductDto cartProductDto = new CartProductDto();
            Item item = itemMapper.selectByPrimaryKey(request.getProductId());
            cartProductDto.setProductId(request.getProductId());
            cartProductDto.setSalePrice(item.getPrice());
            cartProductDto.setProductNum((long)request.getProductNum());
            cartProductDto.setLimitNum((long)item.getLimitNum());
            cartProductDto.setChecked("true");
            cartProductDto.setProductName(item.getTitle());
            if(item.getImage()!=null){
                String img = item.getImage().split(",")[0];
                cartProductDto.setProductImg(img);
            }
            String cartProductDtoString = JSONObject.toJSONString(cartProductDto);
            rMap.put(String.valueOf(request.getProductId()),cartProductDtoString);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getCode());
        } catch (Exception e) {
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            //系统错误,抛出具体异常信息
            response.setMsg(e.getMessage());
        }
        return response;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        try {
            Long userId = request.getUserId();
            RMap<String, String> rMap = redissonClient.getMap(String.valueOf(userId));
            Set<String> products = rMap.keySet();
            for (String productId : products) {
                //将新增的数量更新到购物车,添加结束
                if(request.getItemId()==Long.parseLong(productId)){
                    String s = rMap.get(productId);
                    JSONObject jsonObject = JSON.parseObject(s);
                    jsonObject.put("productNum",request.getNum()+"");
                    jsonObject.put("checked",request.getChecked());
                    rMap.put(productId,JSON.toJSONString(jsonObject));
                    break;
                }
            }
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getCode());
        } catch (Exception e) {
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(e.getMessage());
        }
        return response;
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse response = new CheckAllItemResponse();
        try {
            RMap<String, String> map = redissonClient.getMap(request.getUserId() + "");
            Set<String> productIds = map.keySet();
            for (String productId : productIds) {
                String product = map.get(productId);
                JSONObject jsonObject = JSON.parseObject(product);
                String checked = (String) jsonObject.get("checked");
                if(!request.getChecked().equals(checked)){
                    jsonObject.put("checked",request.getChecked());
                }
                map.put(productId, JSON.toJSONString(jsonObject));
            }
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(e.getMessage());
        }
        return response;
    }

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse deleteCartItemResponse = new DeleteCartItemResponse();
        try{
            request.requestCheck();
            RMap<String, String> map = redissonClient.getMap(request.getUserId().toString());
            map.remove(request.getItemId()+"");
            deleteCartItemResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            deleteCartItemResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            deleteCartItemResponse.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            deleteCartItemResponse.setMsg(e.getMessage());
        }
        return deleteCartItemResponse;
    }

    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne deleteCheckedItemResposne = new DeleteCheckedItemResposne();
        try{


//            RMap<Object, Object> map = redissonClient.getMap(request.getUserId().toString());
//
//            for (Object o : map.keySet()) {
//
//                String value = (String) map.get(o.toString());
//
////                List<CartProductDto> cartProductDtos = JSONObject.parseObject(value,CartProductDto.class);
//
//                CartProductDto cartProductDtos = JSONObject.parseObject(value, CartProductDto.class);
////                String s = JSONObject.toJSONString(cartProductDtos);
//
//                if(cartProductDtos.getChecked().equals("false") ){
//                    map.remove(o.toString());

            request.requestCheck();
            RMap<String, String> map = redissonClient.getMap(request.getUserId().toString());
            for (String productId : map.keySet()) {
                //如果购物车商品json字符串包含""check":"true"",直接删除
                String product = map.get(productId);
                JSONObject jsonObject = JSON.parseObject(product);
                String checked = (String) jsonObject.get("checked");
                if("true".equals(checked)){
                    map.remove(productId);

                }
            }
            deleteCheckedItemResposne.setCode(ShoppingRetCode.SUCCESS.getCode());
            deleteCheckedItemResposne.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }catch (Exception e){
            deleteCheckedItemResposne.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            deleteCheckedItemResposne.setMsg(e.getMessage());
        }
        return deleteCheckedItemResposne;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        return null;
    }
}
